package com.liyunc.demo.filter;
/**
 * Copyright (c) 2018-2022 ThunderSoft
 * All Rights Reserved by Thunder Software Technology Co., Ltd and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with ThunderSoft in writing by applicable law.
 */

import com.liyunc.demo.handler.MyAuthenticationFailureHandler;
import com.liyunc.demo.util.ValidateCodeUtil;
import com.liyunc.demo.validate.ImageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liyuncong
 * @version 1.0
 * @file
 * @brief
 * @details
 * @date 2022-02-21
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2022-02-21               liyuncong        Created
 */
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    private final SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain
    ) throws ServletException, IOException {
        if (request.getRequestURI().equalsIgnoreCase("/api/v1/auth/form")
            && request.getMethod().equalsIgnoreCase("post")) {
            try {
                validateCode(new ServletWebRequest(request));
            } catch (AuthenticationException exception) {
                myAuthenticationFailureHandler.onAuthenticationFailure(request, response,
                    exception);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private void validateCode(ServletWebRequest request)
        throws ServletRequestBindingException {
        ImageCode codeInSession = (ImageCode) sessionStrategy
            .getAttribute(request, ValidateCodeUtil.SESSION_KEY_IMAGE_CODE);
        String codeInRequest =
            ServletRequestUtils.getStringParameter(request.getRequest(), "image");

        if (codeInRequest == null) {
            throw new RuntimeException("验证码为空");
        }
        if (codeInSession == null) {
            throw new RuntimeException("验证码不存在");
        }
        if (codeInSession.isExpire()) {
            sessionStrategy.removeAttribute(request, ValidateCodeUtil.SESSION_KEY_IMAGE_CODE);
            throw new RuntimeException("验证码已过期");
        }
        if (!codeInSession.getCode().equalsIgnoreCase(codeInRequest)) {
            throw new RuntimeException("验证码不正确");
        }
        sessionStrategy.removeAttribute(request, ValidateCodeUtil.SESSION_KEY_IMAGE_CODE);
    }
}
